package edu.wisc.hevea.producer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.protobuf.ServiceException;
import com.wisc.application.ApplicationPolicy;

import edu.wisc.hevea.broker.BrokerManager;
import edu.wisc.hevea.exception.BrokerUnavailableException;
import edu.wisc.hevea.messaging.MessagingServiceClient;

public class Producer {
	private static final Logger logger = LoggerFactory
		      .getLogger(Producer.class);
	
	private String hostName;
	private ApplicationPolicy appPolicy;
	private BrokerManager brokerManager;
	private MessagingServiceClient messagingServiceClient;
	
	public Producer(String hostName, ApplicationPolicy appPolicy) {
		this.sethostName(hostName);
		this.setAppPolicy(appPolicy);
		messagingServiceClient = MessagingServiceClient.getMessagingServiceClient(hostName);
		brokerManager = new BrokerManager(appPolicy,hostName,messagingServiceClient);
	}

	public String gethostName() {
		return hostName;
	}

	public void sethostName(String hostName) {
		this.hostName = hostName;
	}

	public ApplicationPolicy getAppPolicy() {
		return appPolicy;
	}

	public void setAppPolicy(ApplicationPolicy appPolicy) {
		this.appPolicy = appPolicy;
	}
	
	public void sendMessage(String topic, String content)
			throws BrokerUnavailableException, ServiceException {
		String nextBroker = brokerManager.getNextBroker();
		logger.info("Sending message to broker " + nextBroker);
		messagingServiceClient.sendMessage(topic, content, nextBroker);
	}
}
